<script setup lang="ts" name="emergency-plan">
import {
  getCurrentInstance,
  defineComponent,
  onMounted,
  onActivated,
  reactive,
  ref,
  toRaw,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  saveEmergencyCase,
  addEmergencyCaseGroup,
  getEmergencyCaseList,
  getEmergencyCaseInfo,
  getGroupList,
  getGroupUserList,
  deleteEmergencyCase,
  getGroupUserTasks,
  deleteGroupUser,
  deleteEmergencyCaseGroup,
  getUserList,
} from "@/api/server_emergency";
const router = useRouter();
const height = ref(200);
const groupUserList = ref<any[]>([]);
const emergencyCaseInfo = ref<any>({});
const caseGroupList = ref<any>([]);
const userListTotal = ref(0);
let userListForm = ref<any>({
  page: 1,
  pageSize: 20,
});
const activeInfo = ref<any>({});
const groupList = ref<any>([]);
const emergencyCaseList = ref<any>([]);
const userList = ref<any>([]);
const userDialogVisible = ref(false);
const groupDialogVisible = ref(false);
const infoDialogVisible = ref(false);
const taskDialogVisible = ref(false);
const addItem = ref<any>({});
const tasksList = ref<any>([]);

const handleCurrentChange = (page: number) => {
  getGroupUserList_(page);
};
const getUserList_ = async () => {
  let res = await getUserList({
    page: 1,
    pageSize: 10000,
  });
  userList.value = res.list;
};
const emergencyCaseList_ = async () => {
  let res = await getEmergencyCaseList({});
  emergencyCaseList.value = res.emergencyCaseList;
  if (!activeInfo) {
    tabGroup(res.emergencyCaseList[0])
  }
};

const editGroup = (data: any) => {
  ElMessageBox.prompt(
    `${data.emergency_case_id ? "编辑" : "新增"}应急方案`,
    "",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputValue: data.name,
      // inputPattern: /^.{1,100}$/,
      // inputErrorMessage: "请输入内容",
    }
  )
    .then(async ({ value }) => {
      let res = await saveEmergencyCase({
        id: data.emergency_case_id || 0,
        // firstLeader:emergencyCaseInfo.value.first_leader,
        // secondLeader:emergencyCaseInfo.value.second_leader,
        name: value,
      });
      if (res.result == "success") {
        emergencyCaseList_();
      }
    })
    .catch(() => {});
};
const deleteGroup_ = (data: any) => {
  ElMessageBox.confirm(
    `<span>确定要删除 <i style="color:#58B2C5;">${data.name}</i> 吗</span>`,
    "提 示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
      type: "warning",
    }
  ).then(async () => {
    let res = await deleteEmergencyCase({
      caseId: data.emergency_case_id,
    });
    if (res.result == "success") {
      emergencyCaseList_();
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
    }
  });
};

const handleCommand = (command: string | number | object, data: object) => {
  if (command === "edit") {
    editGroup(data);
  }
  if (command === "delete") {
    deleteGroup_(data);
  }
};
const tabGroup = async (item: any) => {
  activeInfo.value = item;
  getEmergencyCaseInfo_();
};
const getEmergencyCaseInfo_ = async () => {
  let res = await getEmergencyCaseInfo({
    caseId: activeInfo.value.emergency_case_id,
  });
  emergencyCaseInfo.value = res.caseInfo || {};
  caseGroupList.value = res.caseGroupList || [];
};
const addUser = async () => {
  userDialogVisible.value = true;
  addItem.value.tasks = [""];
};
const saveUser = async () => {
    let data:any = {}
    if(openAddLeaderType.value === 1){
        data.firstLeader = addItem.value.userId
    }
    if(openAddLeaderType.value === 2){
        data.secondLeader = addItem.value.userId
    }
    let res = await saveEmergencyCase({
        firstLeader:emergencyCaseInfo.value.first_leader,
        secondLeader:emergencyCaseInfo.value.second_leader,
        name:emergencyCaseInfo.value.name,
        id: emergencyCaseInfo.value.emergency_case_id || 0,
        ...data
      });

  if (res.result == "success") {
    userDialogVisible.value = false;
    getEmergencyCaseInfo_();
  }
};
const openAddLeaderType = ref(1)
/* 添加组长 */
const openAddLeader = (type: number)=>{
    openAddLeaderType.value = type
    userDialogVisible.value = true
}
/* 添加组长*/
const addGroup = ()=>{
    groupDialogVisible.value = true
}
const saveGroup = async ()=>{
    let res  = await addEmergencyCaseGroup({
        caseId : emergencyCaseInfo.value.emergency_case_id,
        groupIds : addItem.value.groupIds
    })
     groupDialogVisible.value = false
     getEmergencyCaseInfo_()
}
const getGroupList_ = async () => {
  let res = await getGroupList({});
  groupList.value = res.groupList;
  
  
  
};
const deleteEmergencyCaseGroup_ = async (item:any)=>{
    ElMessageBox.confirm(
    `<span>确定要删除 <i style="color:#58B2C5;">${item.name}</i> 吗</span>`,
    "提 示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      dangerouslyUseHTMLString: true,
      type: "warning",
    }
  ).then(async () => {
    let res = await deleteEmergencyCaseGroup({
       caseId : emergencyCaseInfo.value.emergency_case_id,
       groupId : item.emergency_group_id
    })
    if (res.result == "success") {
       getEmergencyCaseInfo_()
      ElMessage({
        type: "success",
        message: "删除成功!",
      });
    }
  });
}
const currentCase = ref<any>({})
const openDetail = async (item:any)=>{
    infoDialogVisible.value = true
    currentCase.value = item
    getGroupUserList_(1)
}
const getGroupUserList_ = async (page: number) => {
  let res = await getGroupUserList({
    groupId: currentCase.value.emergency_group_id,
    page: page || 1,
    tasks: [],
  });
  groupUserList.value = res.list || [];
  userListTotal.value = res.total || 1;
};
const deleteUser = async (item: any) => {
  let res = await deleteGroupUser({
    groupUserId: item.emergency_group_user_id,
  });
  getGroupUserList_(userListForm.value.page);
};
const groupUserTasks = async (item: any) => {
  let res = await getGroupUserTasks({
    groupId: currentCase.value.emergency_group_id,
    userId: item.user_id,
  });
  return res.groupUserTasks;
};

const taskInfo = async (item: any) => {
  let tasks = await groupUserTasks(item);
  tasksList.value = tasks;
  taskDialogVisible.value = true;
};

onMounted(() => {
  setTimeout(() => {
    let pageTable: any = document.querySelector(".page-table");
    height.value = pageTable.clientHeight;
  }, 50);
  getGroupList_();
  getUserList_();
  emergencyCaseList_();
});
</script>

<template>
  <div class="emergency-plan">
    <div class="page-top">
      <h4>应急预案配置</h4>
    </div>
    <div class="group-info">
      <div class="group-left">
        <div
          class="group-name-item"
          @click="tabGroup(item)"
          :class="{
            active: activeInfo.emergency_case_id == item.emergency_case_id,
          }"
          :key="index"
          v-for="(item, index) in emergencyCaseList"
        >
          <span>{{ item.name }}</span>
          <el-dropdown @command="handleCommand($event, item)">
            <el-icon><MoreFilled /></el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="group-name-add" @click="editGroup({})">
          <el-icon><Plus /></el-icon>
          <span>新增应急方案</span>
        </div>
      </div>
      <div class="group-right">
        <div class="page-top">
          <h4>{{ activeInfo.name }}</h4>
        </div>
        <div class="page-table">
          <div class="leader-info">
            <div class="plan-card" @click="openAddLeader(1)">
              <template v-if="!emergencyCaseInfo.first_leader" >
                <el-icon><Plus /></el-icon>
                <span>添加组长</span>
              </template>
              <div class="info" v-if="emergencyCaseInfo.first_leader">
                <h3 class="line1" v-if="emergencyCaseInfo.firstLeaderInfo">{{ emergencyCaseInfo.firstLeaderInfo.name }}（组长）</h3>
                <div class="line2">
                  <span>
                    <el-icon><PhoneFilled /></el-icon>
                    <span v-if="emergencyCaseInfo.firstLeaderInfo">{{ emergencyCaseInfo.firstLeaderInfo.phone  }}</span>
                  </span>
                  <span class="reset">
                    <el-icon><RefreshRight /></el-icon>
                    <span>重设</span>
                  </span>
                </div>
              </div>
            </div>
            <div class="plan-card" @click="openAddLeader(2)">
              <template v-if="!emergencyCaseInfo.second_leader">
                <el-icon><Plus /></el-icon>
                <span>添加副组长</span>
              </template>
              <div class="info" v-if="emergencyCaseInfo.second_leader">
                <h3 class="line1" v-if="emergencyCaseInfo.secondLeaderInfo">{{ emergencyCaseInfo.secondLeaderInfo.name }}（副组长）</h3>
                <div class="line2">
                  <span>
                    <el-icon><PhoneFilled /></el-icon>
                    <span v-if="emergencyCaseInfo.secondLeaderInfo">{{
                      emergencyCaseInfo.secondLeaderInfo.phone 
                    }}</span>
                  </span>
                  <span class="reset">
                    <el-icon><RefreshRight /></el-icon>
                    <span>重设</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
          <div class="groups-info">
            <div class="plan-card" @click="addGroup">
              <el-icon><Plus /></el-icon>
              <span>添加应急组</span>
            </div>
            <div class="plan-card" :key="index" v-for="(item,index) in caseGroupList">
                <div class="info">
                <h3 class="line1">{{ item.name }}</h3>
                <div class="line2">
                  <span @click="deleteEmergencyCaseGroup_(item)">
                    <el-icon><Delete /></el-icon>
                    <span>删除</span>
                  </span>
                  <span @click="openDetail(item)">
                    <span>查看详情</span>
                  </span>
                </div>
                </div>
            </div>
          </div>

        </div>
      </div>
    </div>

   <el-dialog :close-on-click-modal="false"  :title="openAddLeaderType==2?'添加副组长':'添加组长'" v-model="userDialogVisible" width="400px">
      <el-select
            filterable
            clearable
            style="width: 80%"
            v-model="addItem.userId"
            placeholder="请选择"
          >
            <el-option
              :value="c.user_id"
              :label="c.name"
              :key="index"
              v-for="(c, index) in userList"
            >
              <span style="float: left">{{ c.name }}</span>
              <span
                style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                "
                >{{ c.phone }}</span
              >
            </el-option>
          </el-select>

          <div style="text-align: right;padding:20px;">
            <el-button @click="userDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveUser">确定</el-button>
          </div>
    </el-dialog>
   <el-dialog :close-on-click-modal="false"  title="添加应急组" v-model="groupDialogVisible" width="400px">
      <el-select
            filterable
            clearable
            multiple
            style="width: 80%"
            v-model="addItem.groupIds"
            placeholder="请选择"
          >
            <el-option
              :value="c.emergency_group_id"
              :label="c.name"
              :key="index"
              v-for="(c, index) in groupList"
            >
            </el-option>
          </el-select>

          <div style="text-align: right;padding:20px;">
            <el-button @click="userDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveGroup">确定</el-button>
          </div>
    </el-dialog>


   <el-dialog :close-on-click-modal="false"  title="详情" v-model="infoDialogVisible" width="500px">
        <el-table :data="groupUserList" :height="height" size="small" border>
            <el-table-column
              label="序号"
              prop="emergency_group_user_id"
            ></el-table-column>
            <el-table-column
              label="姓名"
              prop="userInfo.name"
            ></el-table-column>
            <el-table-column
              label="电话"
              prop="userInfo.phone"
            ></el-table-column>
            <el-table-column
              label="部门"
              prop="userInfo.deptName"
            ></el-table-column>
            <el-table-column label="操作" prop="">
              <template #default="scope">
                <el-button link size="small" @click="taskInfo(scope.row)"
                  >任务详情</el-button
                >
                <el-button
                  link
                  size="small"
                  @click="deleteUser(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
      <el-pagination
          style="text-align: right"
          layout="prev, pager, next"
          :page-size="20"
          @current-change="handleCurrentChange"
          v-model:currentPage="userListForm.page"
          :total="userListTotal"
        >
        </el-pagination>
    </el-dialog>
   <el-dialog :close-on-click-modal="false"  title="任务详情" v-model="taskDialogVisible" width="500px">
      <div style="max-height: 500px; overflow: auto">
        <el-form size="small" label-width="80px" class="warning-form-inline">
          <el-form-item
            :label="`任务${index + 1}`"
            :key="index"
            v-for="(item, index) in tasksList || []"
          >
            <div style="font-weight: bold">{{ item }}</div>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.emergency-plan {
  width: 100%;
  height: 100%;
  .page-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .group-info {
    height: calc(100% - 30px);
    display: flex;
    align-items: center;
    .group-left {
      height: 100%;
      width: 240px;
      flex-shrink: 0;
      overflow-x: hidden;
      overflow-y: auto;
      border: 1px solid #414243;
      .group-name-item {
        width: 240px;
        height: 40px;
        line-height: 40px;
        position: relative;
        padding: 0 30px;
        cursor: pointer;
        &.active {
          background: #3f74a694;
        }
        .el-dropdown {
          transform: rotate(90deg);
          position: absolute;
          right: 5px;
          top: 10px;
          cursor: pointer;
        }
      }
      .group-name-add {
        width: 192px;
        height: 40px;
        line-height: 40px;
        margin: 10px auto;
        border: 1px dashed #d9d9d9;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }
    }
    .group-right {
      height: 100%;
      flex: 1;
      padding: 0 10px;
      .page-top{
        height:30px;
      }
      .page-table {
        margin-top: 10px;
        height: calc(100% - 80px);
        .leader-info {
          display: flex;
        }
        .groups-info {
          display: flex;
          justify-content: flex-start;
          flex-wrap: wrap;
        }
        .plan-card {
          width: 236px;
          height: 98px;
          padding: 10px 20px;
          border-radius: 2px;
          margin: 10px;
          border: 1px dashed #3ba4ba;
          align-self: flex-start;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
          .info {
            width: 100%;
            line-height: 30px;
            i {
              font-size: 18px;
              position: relative;
              top: 3px;
            }
            .reset {
              cursor: pointer;
            }
            .line2 {
              display: flex;
              justify-content: space-between;
              align-items: center;
            }
          }
          &.isSet {
            border: 1px solid rgba(255, 255, 255, 0.8);
          }
        }
      }
    }
  }
}
.group-add-task {
  width: 180px;
  height: 30px;
  line-height: 40px;
  margin: 10px 0;
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
</style>
